#include "recv.h"
int main(int argc, char const *argv[])
{
    // 创建套数据报接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket err");
        return -1;
    }
    // 2.填充结构体
    struct sockaddr_in saddr;
    char buf[256] = {0};
    char password[] = "23072_7_zzj";

    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(PORT);
    saddr.sin_addr.s_addr = inet_addr("0.0.0.0");

    
    if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
    {
        perror("bind err");
        return -1;
    }
    pthread_t tid;
    char dev_name[32] = "23072_7_litianyuan\n";
    while (1)
    {
        // 接收对方发送的消息
        struct sockaddr soft_addr;
        struct sockaddr *soft_addr_ptr = &soft_addr;
        socklen_t addrlen = sizeof(soft_addr);
        int r = recvfrom(sockfd, buf, sizeof(buf), 0, &soft_addr, &addrlen);
        if (r < 0)
        {
            perror("recvfrom err");
            return -1;
        }
        else
        {
            if (!strcmp(buf, password))
            {
                sendto(sockfd, dev_name, sizeof(dev_name), 0, (struct sockaddr *)&soft_addr, addrlen);
                printf("%s\n", buf);
                memset(buf, 0, sizeof(buf));
            }
            else if (!strcmp(buf, "TCPCONNECT"))
            {
                //创建线程
                if (pthread_create(&tid, NULL, tcpfunc, soft_addr_ptr))
                {
                    perror("create  err");
                    return -1;
                }
                pthread_detach(tid);
            }
        }
    }
    close(sockfd);
    return 0;
}
